import request from "@/utils/request";
import { Select } from "antd";
import { Component } from "react";

interface IProps {
  value?: number[];
  onChange?: (value: number[]) => void;
}

interface IState {
  list: Role.Item[];
}

export default class RoleSelect extends Component<IProps, IState> {
  state: Readonly<IState> = {
    list: [],
  };

  refresh = () => {
    request<Role.Item[]>({
      url: "/admin/base/sys/role/list",
      method: "POST",
    }).then((resp) => {
      this.setState({ list: resp });
    });
  };

  render() {
    // 计算属性
    const max = 3;
    const options = this.state.list.map((item) => {
      // 控制需要禁用的项目的条件
      if (
        this.props.value &&
        !this.props.value?.includes(item.id) &&
        this.props.value?.length >= max
      ) {
        return {
          ...item,
          disabled: true,
        };
      } else {
        return {
          ...item,
          disabled: false,
        };
      }
    });

    return (
      <Select
        mode="multiple"
        value={this.props.value}
        onChange={this.props.onChange}
        fieldNames={{ value: "id", label: "name" }}
        options={options}
      />
    );
  }

  componentDidMount() {
    this.refresh();
  }
}
